package br.usjt.mazerobot.pc.comunicacao;

import br.usjt.mazerobot.commons.comunicacao.Pacote;
import br.usjt.mazerobot.pc.util.Logger;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import lejos.pc.comm.NXTConnector;

public class ComunicadorBluetooth implements Comunicador {

    private NXTConnector connector;
    private DataOutputStream outputStream;
    private DataInputStream inputStream;

    private Logger logger = new Logger();

    @Override
    public boolean conectar() {
        connector = new NXTConnector();
        boolean conectado = false;
        conectado = connector.connectTo("btspp://");
        outputStream = connector.getDataOut();
        inputStream = connector.getDataIn();
        return conectado;
    }

    @Override
    public void desconectar() {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                logger.erro(ex.getMessage());
            }
        }

        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                logger.erro(ex.getMessage());
            }
        }

        if (connector != null) {
            try {
                connector.close();
            } catch (IOException ex) {
                logger.erro(ex.getMessage());
            }
        }
    }

    @Override
    public void enviar(Pacote pacote) {
        try {
            outputStream.write(pacote.getDados());
            outputStream.flush();
        } catch (IOException ex) {
            logger.erro(ex.getMessage());
        }
    }

    @Override
    public Pacote receber() {
        Pacote pacote = new Pacote();
        try {
            inputStream.read(pacote.getDados());
        } catch (IOException ex) {
            logger.erro(String.format("Erro ao receber pacote. - %s", ex.getMessage()));
        }
        return pacote;
    }
}
